package com.yswl.pri;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import static org.junit.Assert.assertEquals;

/**
 * Created by kangpAdministrator on 2018/5/18 0018.
 * Emial kangpeng@yunhetong.net
 */

public class HashMapSortT {
    class User {
        public User(int age, String name) {
            this.age = age;
            this.name = name;
        }

        int age;
        String name;

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    /**
     * 根据hashmap value中的值排序
     */
    @Test
    public void sortHashEntry() {
        Map<Integer, User> map = new HashMap<>();
        map.put(1, new User(22, "KK"));
        map.put(5, new User(25, "PP"));
        map.put(7, new User(27, "YY"));
        map.put(3, new User(23, "WW"));
        map.put(4, new User(4, "WW"));
        System.out.println("old " + map);
        for (Map.Entry<Integer, User> entry : map.entrySet()) {
            System.out.print("--entry tostring ---->> " + entry.toString());
            System.out.println(" --entry hashcode  ---->> " +entry.hashCode());
            System.out.print("--entry key tostring ---->> " + entry.getKey().toString());
            System.out.println(" --entry key hashcode ---->> " +entry.getKey().hashCode());
        }

        Map<Integer, User> sortMap = sortMap(map);
        System.out.println("new " + sortMap);
    }


    private Map<Integer, User> sortMap(Map<Integer, User> map) {
        Set<Map.Entry<Integer, User>> set = map.entrySet();
        List<Map.Entry<Integer, User>> list = new ArrayList<>(set);
        Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
            @Override
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
                return o1.getValue().age - o2.getValue().age;
            }
        });
        LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<Integer, User> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        return linkedHashMap;
    }
}
